/*
    9. Write a program in C to replace a specific line with another text in a file.

    Assume that the content of the file test.txt is :                                                                       
    test line 1                                                                                                   
    test line 2                                                                                                   
    test line 3                                                                                                   
    test line 4                                                                                                   
    Test Data :
    Input the file name to be opened : test.txt
    Input the content of the new line : Yes, I am the new text instead of test line 2
    Input the line no you want to replace : 2
    Expected Output :

    Replacement did successfully..!! 
*/

#include <stdio.h>

#define MAX_STR 1024
#define MAX_FILENAME 64

int main(void)
{
    FILE *fp1, *fp2;
    char filename[MAX_FILENAME];
    char tmpfile[] = "tem.txt";
    char newstr[MAX_STR];
    char tmpstr[MAX_STR];
    int lineno, curline = 0;
    printf("Input the file name to be opened : ");
    scanf("%s", filename);
    printf("Input the content of the new line : ");
    fflush(stdin);
    gets(newstr);
    printf("Input the line NO. you want to replace : ");
    fflush(stdin);
    scanf("%d", &lineno);

    if((fp1 = fopen(filename, "r")) == NULL){
        printf("Open file %s filed!", filename);
        return -1;
    }
    if((fp2 = fopen(tmpfile, "w+")) == NULL){
        printf("Open file %s filed!", tmpfile);
        return -1;
    }
    while(NULL != (fgets(tmpstr, MAX_STR, fp1))){
        curline++;
        if(lineno == curline){
            fputs(newstr, fp2);
            fputc('\n', fp2);
        }else{
            fputs(tmpstr, fp2);
        }
    }
    if(fclose(fp1) == EOF){
        printf("close filed at line %d", __LINE__);
        return -1;
    }
    if(fclose(fp2) == EOF){
        printf("close filed at line %d", __LINE__);
        return -1;
    }
    if(remove(filename) == -1){
        printf("remove filed at line %d", __LINE__);
        return -1;
    }
    if(rename(tmpfile, filename) == -1){
        printf("rename filed at line %d", __LINE__);
        return -1;
    }
    printf("Replacement did successfully..!!");

    return 0;
}